﻿// 注入
function injectScripts(src) {
  var s = document.createElement("script");
  s.src = chrome.extension.getURL(src);
  s.onload = function() {
    this.remove();
  };
  (document.head || document.documentElement).appendChild(s);
}

injectScripts('scripts/xmlHttp.js')
// injectScripts('scripts/xlsx.js')

let mouseEvent = document.createEvent('MouseEvent');
let clickEvent = document.createEvent('MouseEvent');
let mouseMoveEvent = document.createEvent('MouseEvent');
let username = sessionStorage.getItem('username');
let password = sessionStorage.getItem('password');
let infoReceived = false;

mouseEvent.initMouseEvent('mousedown', true, true, document.defaultView, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
clickEvent.initMouseEvent('click', true, true, document.defaultView, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
mouseMoveEvent.initMouseEvent('mousemove', true, true, document.defaultView, 0, 0, 0, 0, 0, false, false, false, false, 0, null)

if (username && password) {
  infoReceived = true;
}

// 如果本地缓存没有用户信息，需要总安全中心拿
chrome.runtime.sendMessage({ type: 'need-userInfo' })

// 获取登录信息
chrome.runtime.onMessage.addListener((req, sender, sendRes) => {
  if (req.type === 'send-userinfo') {
    username = req.username;
    password = req.password;
    sessionStorage.setItem('username', username);
    sessionStorage.setItem('password', password);
    infoReceived = true;
  } else if(req.type === 'generate-excel') {
    // 用于生成excel并下载
    if (location.href.indexOf('?target=generateExcel') !== -1) {
      const pagelist = req.data

      // init filesaver
      var saveAs=saveAs||function(e){"use strict";if(typeof e==="undefined"||typeof navigator!=="undefined"&&/MSIE [1-9]\./.test(navigator.userAgent)){return}var t=e.document,n=function(){return e.URL||e.webkitURL||e},r=t.createElementNS("http://www.w3.org/1999/xhtml","a"),o="download"in r,a=function(e){var t=new MouseEvent("click");e.dispatchEvent(t)},i=/constructor/i.test(e.HTMLElement)||e.safari,f=/CriOS\/[\d]+/.test(navigator.userAgent),u=function(t){(e.setImmediate||e.setTimeout)(function(){throw t},0)},s="application/octet-stream",d=1e3*40,c=function(e){var t=function(){if(typeof e==="string"){n().revokeObjectURL(e)}else{e.remove()}};setTimeout(t,d)},l=function(e,t,n){t=[].concat(t);var r=t.length;while(r--){var o=e["on"+t[r]];if(typeof o==="function"){try{o.call(e,n||e)}catch(a){u(a)}}}},p=function(e){if(/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(e.type)){return new Blob([String.fromCharCode(65279),e],{type:e.type})}return e},v=function(t,u,d){if(!d){t=p(t)}var v=this,w=t.type,m=w===s,y,h=function(){l(v,"writestart progress write writeend".split(" "))},S=function(){if((f||m&&i)&&e.FileReader){var r=new FileReader;r.onloadend=function(){var t=f?r.result:r.result.replace(/^data:[^;]*;/,"data:attachment/file;");var n=e.open(t,"_blank");if(!n)e.location.href=t;t=undefined;v.readyState=v.DONE;h()};r.readAsDataURL(t);v.readyState=v.INIT;return}if(!y){y=n().createObjectURL(t)}if(m){e.location.href=y}else{var o=e.open(y,"_blank");if(!o){e.location.href=y}}v.readyState=v.DONE;h();c(y)};v.readyState=v.INIT;if(o){y=n().createObjectURL(t);setTimeout(function(){r.href=y;r.download=u;a(r);h();c(y);v.readyState=v.DONE});return}S()},w=v.prototype,m=function(e,t,n){return new v(e,t||e.name||"download",n)};if(typeof navigator!=="undefined"&&navigator.msSaveOrOpenBlob){return function(e,t,n){t=t||e.name||"download";if(!n){e=p(e)}return navigator.msSaveOrOpenBlob(e,t)}}w.abort=function(){};w.readyState=w.INIT=0;w.WRITING=1;w.DONE=2;w.error=w.onwritestart=w.onprogress=w.onwrite=w.onabort=w.onerror=w.onwriteend=null;return m}(typeof self!=="undefined"&&self||typeof window!=="undefined"&&window||this.content);if(typeof module!=="undefined"&&module.exports){module.exports.saveAs=saveAs}else if(typeof define!=="undefined"&&define!==null&&define.amd!==null){define("FileSaver.js",function(){return saveAs})}

      // init XLSX
      /* xlsx.js (C) 2013-2015 SheetJS -- http://sheetjs.com */



      document.body.innerHTML = `
        <p>已接收到插件传来的数据，正在生成excel，请稍等。。。</p>
      `
    }
  }
})

setTimeout(() => {
  // 爬订单指定页面
  if (location.href.indexOf('/report/zone/zone_self?type=download') !== -1) {
    const currentTime = Date.now()
    const today = new Date(currentTime).toLocaleDateString().replace(/\//g, '-')
    const startDay = new Date(currentTime - 60 * 1000 * 60 * 24 * 3).toLocaleDateString().replace(/\//g, '-')

    // 下载自助推广统计信息的报表链接
    const downStateUrl =
      '/report/selfRpt.json?DownloadID=DOWNLOAD_REPORT_REBORN_DETAIL&adzoneId=&startTime=STARTTIME&endTime=ENDTIME'
      .replace('STARTTIME', startDay)
      .replace('ENDTIME', today);

    // 下载淘宝客推广订单的链接
    const orderUrl =
      '/report/getTbkPaymentDetails.json?queryType=QUERYTYPE&payStatus=PAYSTATUS&DownloadID=DOWNLOAD_REPORT_INCOME_NEW&startTime=STARTTIME&endTime=ENDTIME'
      .replace('STARTTIME', startDay)
      .replace('ENDTIME', today);
    // 全量订单
    const downAllOrderUrl =
      orderUrl
      .replace('QUERYTYPE', 1)
      .replace('PAYSTATUS', '');
    // 结算订单
    const downFinishedOrderUrl =
      orderUrl
      .replace('QUERYTYPE', 3)
      .replace('PAYSTATUS', 3);
    // 失效订单
    const downAbatedOrderUrl =
      orderUrl
      .replace('QUERYTYPE', 1)
      .replace('PAYSTATUS', 13);

    // 下载第三方服务商推广的订单
    const thirdOrderUrl =
      '/report/getTbkThirdPaymentDetails.json?queryType=QUERYTYPE&payStatus=PAYSTATUS&DownloadID=DOWNLOAD_REPORT_TK3_PUB&startTime=STARTTIME&endTime=ENDTIME'
      .replace('STARTTIME', startDay)
      .replace('ENDTIME', today);
    // 全量订单
    const downThirdAllOrderUrl =
      thirdOrderUrl
      .replace('QUERYTYPE', 2)
      .replace('PAYSTATUS', '');
    // 结算订单
    const downThirdFinishedOrderUrl =
      thirdOrderUrl
      .replace('QUERYTYPE', 4)
      .replace('PAYSTATUS', 3);
    // 失效订单
    const downThirdAbatedOrderUrl =
      thirdOrderUrl
      .replace('QUERYTYPE', 2)
      .replace('PAYSTATUS', 13);

    setTimeout(() => {
      // 清空hmtl
      document.body.innerHTML = `
        <div>
          <p style="color: black;font-weight: bold;font-size: 32px;">${document.querySelector('#J_menu_product .menu-username').textContent}</p>
          <p style="color: red; font-size: 26px;">该窗口是爬取订单专用，勿动。如果不小心关了也不要紧（你也关不掉）</p>
          <p style="color: green;">建议你从这里新开窗口进入</p>
          <img src="" title="点击任务栏chrome浏览器小图标，点击对应的插件账号进入"/>
        </div>
        <div><a id="downState" href="${downStateUrl}">自助推广报表</a></div>
        <div><a id="downAllOrder" href="${downAllOrderUrl}">淘宝客推广全部订单报表</a></div>
        <div><a id="downFinishedOrder" href="${downFinishedOrderUrl}">淘宝客推广结算订单报表</a></div>
        <div><a id="downAbatedOrder" href="${downAbatedOrderUrl}">淘宝客推广失效订单报表</a></div>
        <div><a id="downThirdAllOrder" href="${downThirdAllOrderUrl}">第三方服务商推广全部订单报表</a></div>
        <div><a id="downThirdFinishedOrder" href="${downThirdFinishedOrderUrl}">第三方服务商推广结算订单报表</a></div>
        <div><a id="downThirdAbatedOrder" href="${downThirdAbatedOrderUrl}">第三方服务商推广失效订单报表</a></div>
      `
    }, 30 * 1000)

    function downloadFiles() {
      // 推广报表
      setTimeout(() => {
        if (document.querySelector('#downState')) {
          location.href.indexOf('/report/zone/zone_self?type=download') !== -1 &&
            document.querySelector('#downState').click();
        } else {
          document.body.innerHTML += `<div><a id="downState" href="${downStateUrl}">自助推广报表</a></div>`
        }
      }, 0)
      // 下载全部淘客订单
      setTimeout(() => {
        if (document.querySelector('#downAllOrder')) {
          location.href.indexOf('/report/zone/zone_self?type=download') !== -1 &&
            document.querySelector('#downAllOrder').click();
        } else {
          document.body.innerHTML += `<div><a id="downAllOrder" href="${downAllOrderUrl}">淘宝客推广全部订单报表</a></div>`
        }
      }, (30 + Math.floor(Math.random() * 10)) * 1000)
      // 偏移3min下载全部第三方服务商订单
      setTimeout(() => {
        if (document.querySelector('#downThirdAllOrder')) {
          location.href.indexOf('/report/zone/zone_self?type=download') !== -1 &&
            document.querySelector('#downThirdAllOrder').click();
        } else {
          document.body.innerHTML += `<div><a id="downThirdAllOrder" href="${downThirdAllOrderUrl}">第三方服务商推广全部订单报表</a></div>`
        }
      }, (2 * 60 + Math.floor(Math.random() * 60)) * 1000)
      // 偏移3min下载淘宝客结算订单
      setTimeout(() => {
        if (document.querySelector('#downFinishedOrder')) {
          location.href.indexOf('/report/zone/zone_self?type=download') !== -1 &&
            document.querySelector('#downFinishedOrder').click();
        } else {
          document.body.innerHTML += `<div><a id="downFinishedOrder" href="${downFinishedOrderUrl}">淘宝客推广结算订单报表</a></div>`
        }
      }, (5 * 60 + Math.floor(Math.random() * 60)) * 1000)

      // 2分钟后下载第三方服务商结算订单
      setTimeout(() => {
        if (document.querySelector('#downThirdFinishedOrder')) {
          location.href.indexOf('/report/zone/zone_self?type=download') !== -1 &&
            document.querySelector('#downThirdFinishedOrder').click();
        } else {
          document.body.innerHTML += `<div><a id="downThirdFinishedOrder" href="${downThirdFinishedOrderUrl}">第三方服务商推广结算订单报表</a></div>`
        }
      }, (7 * 60 + Math.floor(Math.random() * 60)) * 1000)
      // 偏移3min下载淘宝客失效订单
      setTimeout(() => {
        if (document.querySelector('#downAbatedOrder')) {
          location.href.indexOf('/report/zone/zone_self?type=download') !== -1 &&
            document.querySelector('#downAbatedOrder').click();
        } else {
          document.body.innerHTML += `<div><a id="downAbatedOrder" href="${downAbatedOrderUrl}">淘宝客推广失效订单报表</a></div>`
        }
      }, (10 * 60 + Math.floor(Math.random() * 60)) * 1000)
      // 偏移3min下载第三方服务商失效订单
      setTimeout(() => {
        if (document.querySelector('#downThirdAbatedOrder')) {
          location.href.indexOf('/report/zone/zone_self?type=download') !== -1 &&
            document.querySelector('#downThirdAbatedOrder').click();
        } else {
          document.body.innerHTML += `<div><a id="downThirdAbatedOrder" href="${downThirdAbatedOrderUrl}">第三方服务商推广失效订单报表</a></div>`
        }
      }, (13 + Math.floor(Math.random() * 60)) * 60 * 1000)
      // 偏移2min去刷新session
      setTimeout(() => {
        chrome.runtime.sendMessage({type: 'reload-session'})
      }, (15 + Math.floor(Math.random() * 60)) * 60 * 1000)
    }

    // 让子弹飞一会儿
    const intervalId = setInterval(() => {
      if (location.href.indexOf('/report/zone/zone_self?type=download') !== -1) {
        clearInterval(intervalId)
        downloadFiles()
      }
    }, 1000)
  }
}, 5000)

  // 维持登录
  // if (location.href.indexOf(`http://pub.alimama.com/myunion.htm?spm=${localStorage.getItem('spm')}`) !== -1) {
  //   let intervalId = setInterval(_ => {
  //     let btn = document.querySelector('.close');
  //     let messageTrigger = document.querySelector('.message-trigger');
  //     let travel = (mouseEvent, clickEvent) => {
  //       // 走一遍页面
  //       setTimeout(_ => {
  //         document.querySelector('[href="#!/myunion/overview"]').dispatchEvent(mouseEvent)
  //         document.querySelector('[href="#!/myunion/overview"]').dispatchEvent(clickEvent)
  //       }, 1000)

  //       setTimeout(_ => {
  //         document.querySelector('[href="#!/myunion/message"]').dispatchEvent(mouseEvent)
  //         document.querySelector('[href="#!/myunion/message"]').dispatchEvent(clickEvent)
  //       }, 2000)

  //       setTimeout(_ => {
  //         document.querySelector('[href="#!/promo/self/items"]').dispatchEvent(mouseEvent)
  //         document.querySelector('[href="#!/promo/self/items"]').dispatchEvent(clickEvent)
  //       }, 3000)

  //       setTimeout(_ => {
  //         document.querySelector('[href="#!/promo/self/links"]').dispatchEvent(mouseEvent)
  //         document.querySelector('[href="#!/promo/self/links"]').dispatchEvent(clickEvent)
  //       }, 4000)

  //       setTimeout(_ => {
  //         document.querySelector('[href="#!/promo/taobao/widget_publish"]').dispatchEvent(mouseEvent)
  //         document.querySelector('[href="#!/promo/taobao/widget_publish"]').dispatchEvent(clickEvent)
  //       }, 5000)

  //       setTimeout(_ => {
  //         document.querySelector('[href="#!/promo/taobao/coupon"]').dispatchEvent(mouseEvent)
  //         document.querySelector('[href="#!/promo/taobao/coupon"]').dispatchEvent(clickEvent)
  //       }, 6000)

  //       setTimeout(_ => {
  //         document.querySelector('[href="#!/promo/taobao/software"]').dispatchEvent(mouseEvent)
  //         document.querySelector('[href="#!/promo/taobao/software"]').dispatchEvent(clickEvent)
  //       }, 7000)

  //       setTimeout(_ => {
  //         document.querySelector('[href="#!/promo/act/activity"]').dispatchEvent(mouseEvent)
  //         document.querySelector('[href="#!/promo/act/activity"]').dispatchEvent(clickEvent)
  //       }, 8000)

  //       setTimeout(_ => {
  //         document.querySelector('[href="#!/promo/act/activity_seller"]').dispatchEvent(mouseEvent)
  //         document.querySelector('[href="#!/promo/act/activity_seller"]').dispatchEvent(clickEvent)
  //       }, 9000)

  //       setTimeout(_ => {
  //         document.querySelector('[href="#!/promo/act/activity_cpa"]').dispatchEvent(mouseEvent)
  //         document.querySelector('[href="#!/promo/act/activity_cpa"]').dispatchEvent(clickEvent)
  //       }, 10000)

  //       setTimeout(_ => {
  //         document.querySelector('[href="#!/promo/extra/aliyun"]').dispatchEvent(mouseEvent)
  //         document.querySelector('[href="#!/promo/extra/aliyun"]').dispatchEvent(clickEvent)
  //       }, 11000)

  //       setTimeout(_ => {
  //         document.querySelector('[href="#!/promo/extra/alitrip"]').dispatchEvent(mouseEvent)
  //         document.querySelector('[href="#!/promo/extra/alitrip"]').dispatchEvent(clickEvent)
  //       }, 12000)

  //       setTimeout(_ => {
  //         document.querySelector('[href="#!/manage/site/site"]').dispatchEvent(mouseEvent)
  //         document.querySelector('[href="#!/manage/site/site"]').dispatchEvent(clickEvent)
  //       }, 13000)

  //       setTimeout(_ => {
  //         document.querySelector('[href="#!/manage/zone/zone"]').dispatchEvent(mouseEvent)
  //         document.querySelector('[href="#!/manage/zone/zone"]').dispatchEvent(clickEvent)
  //       }, 14000)

  //       setTimeout(_ => {
  //         document.querySelector('[href="#!/manage/channel/channel"]').dispatchEvent(mouseEvent)
  //         document.querySelector('[href="#!/manage/channel/channel"]').dispatchEvent(clickEvent)
  //       }, 15000)

  //       setTimeout(_ => {
  //         document.querySelector('[href="#!/manage/campaign/campaign"]').dispatchEvent(mouseEvent)
  //         document.querySelector('[href="#!/manage/campaign/campaign"]').dispatchEvent(clickEvent)
  //       }, 16000)

  //       setTimeout(_ => {
  //         document.querySelector('[href="#!/manage/software/list"]').dispatchEvent(mouseEvent)
  //         document.querySelector('[href="#!/manage/software/list"]').dispatchEvent(clickEvent)
  //       }, 17000)
  //     }
  //     if (btn) {
  //       clearInterval(intervalId);
  //       let mouseEvent = document.createEvent('MouseEvent');
  //       mouseEvent.initMouseEvent('mousedown', true, true, document.defaultView, 0, 0, 0, 0, 0, false, false, false, false, 0, null)

  //       // 隐藏公告
  //       btn.dispatchEvent(mouseEvent);

  //       setTimeout(_ => {
  //         travel(mouseEvent, clickEvent)
  //       }, 10000)
  //     } else if (messageTrigger) {
  //       clearInterval(intervalId);

  //       // 展现公告
  //       messageTrigger.dispatchEvent(mouseEvent);
  //       messageTrigger.dispatchEvent(clickEvent);

  //       setTimeout(_ => {
  //         travel(mouseEvent, clickEvent)
  //       }, 10000)
  //     }

  //   }, 500);
  // }

// 当跳转到阿里妈妈首页时，获取并设置spm
if (location.href === 'https://pub.alimama.com/' ||
location.href === 'http://pub.alimama.com/') {
  let intervalId = setInterval(_ => {
    let btn = document.querySelector('a.login-enter');
    if (btn) {
      clearInterval(intervalId);
      btn.onclick = function (e) {
        let nextHref = e.target.href;
        let spm = nextHref.split('?spm=')[1];
        localStorage.setItem('spm', spm);
        chrome.runtime.sendMessage({type: 'login-succeed', spm});
      }

      // 模拟mousedown事件，生成spm
      let mouseEvent = document.createEvent('MouseEvent')
      mouseEvent.initMouseEvent('mousedown', true, true, document.defaultView, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
      btn.dispatchEvent(mouseEvent);
      setTimeout(_ => {
        btn.click();
      }, 1500)
    }
  }, 2000);
}

if (location.href.indexOf('login.taobao.com/member/login.jhtml') !== -1) {
  let passwordEle = null;
  let usernameEle = null;
  let loginBtn = null;
  // let passwordInput = null;
  // 自检是否已经滑动验证失败了
  setInterval(() => {
    if (document.querySelector('.errloading')) {
      chrome.runtime.sendMessage({type: 'scroll-failed'});
    }
  }, 100)
  let loginBtnInterval = setInterval(() => {

    // 登录按钮是否加载完成
    loginBtn = document.querySelector('#J_SubmitStatic');
    if (loginBtn) {
      clearInterval(loginBtnInterval);
      loginBtn.textContent = '自动登录中，请稍等...';
      loginBtn.disabled = false;

      // 判断用户名和密码输入框是否渲染完成
      let inputInterval = setInterval(() => {
        passwordEle = document.querySelector('#TPL_password_1');
        usernameEle = document.querySelector('#TPL_username_1');
        loginBtn.onclick = function () {
          password = passwordEle.value;
          username = usernameEle.value;
          chrome.runtime.sendMessage({type: 'get-userinfo', username, password});
        }
        if (passwordEle && usernameEle && infoReceived) {
          clearInterval(inputInterval);

          // 判断是否有滑动验证组件,
          // 如果没有滑动验证组件，直接登录
          if (
            window.getComputedStyle(
              document.querySelector('#nocaptcha')
            ).display === 'none') {
            passwordEle.value = password;
            usernameEle.value = username;
            loginBtn.textContent = `登    录`;
            loginBtn.disabled = false;
            setTimeout(() => {
              document.querySelector('#J_SubmitStatic').click();
            }, 2000)
          } else {

            // 尝试修改localStorage，滑块校验貌似与这个有关
            // 这一组是写死的，因为这一组值可以让滑块校验通过
            // resetLocalStorage()

            // 如果有滑动验证组件，先改名，方便通过滑动验证
            passwordEle.value = password;
            usernameEle.value = username + new Date().getMilliseconds();

            // 开始滑动验证逻辑
            let btn = document.querySelector('#nc_1_n1z');
            let bg = document.querySelector('#nc_1__bg');

            // 通知background清空当前域缓存
            // chrome.runtime.sendMessage({type: 'clear-cookie'})

            // 清除cookie后滑动滑块
            setTimeout(_ => {
              let mouseDownStart = new MouseEvent('mousedown', {
                clientX: 800,
                clientY: 400,
                view: window,
                buttons: 1,
                button: 0,
                bubbles: true,
                cancelable: true
              })

              // reset，因为淘宝登录页对这个值的设置有interval更新
              // resetLocalStorage()
              let mouseDown = new MouseEvent('mousedown', {
                clientX: 800,
                clientY: 400,
                view: window,
                buttons: 1,
                button: 0,
                bubbles: true,
                cancelable: true
              })

              // reset，因为淘宝登录页对这个值的设置有interval更新
              // resetLocalStorage()
              let mouseMove = new MouseEvent('mousemove', {
                clientX: 800,
                clientY: 400,
                view: window,
                buttons: 1,
                button: 0,
                bubbles: true,
                cancelable: true
              })

              btn.dispatchEvent(mouseDownStart);
              document.dispatchEvent(mouseMove);

              setTimeout(() => {
                btn.style.left = '50px';
                bg.style.width = '50px';
              }, 1000)

              setTimeout(() => {
                btn.style.left = '80px';
                bg.style.width = '80px';
              }, 1500)

              setTimeout(() => {
                btn.style.left = '120px';
                bg.style.width = '120px';
              }, 2000)

              setTimeout(() => {
                btn.style.left = '170px';
                bg.style.width = '170px';
              }, 2500)

              setTimeout(() => {
                btn.style.left = '190px';
                bg.style.width = '190px';
              }, 3000)

              setTimeout(() => {
                btn.style.left = '200px';
                bg.style.width = '200px';
              }, 3500)

              setTimeout(() => {
                btn.style.left = '210px';
                bg.style.width = '210px';
              }, 4000)

              setTimeout(() => {
                btn.dispatchEvent(mouseDown);
                document.dispatchEvent(mouseMove);
              }, 4500);

              setTimeout(() => {
                // resetLocalStorage()
                // resetLocalStorage()
                loginBtn.disabled = false;
                loginBtn.textContent = `登    录`;

                // 改回正确昵称
                setTimeout(() => {
                  usernameEle.value = username;

                  setTimeout(() => {
                    // resetLocalStorage()
                    document.querySelector('#J_SubmitStatic').click();
                  }, 2000)
                }, 2000)
              }, 5000)
            }, 1000)
          }
        }
      }, 200)
    }
  }, 200);

  // 如果3分钟都还没有登录完，重刷页面
  setTimeout(() => {
    location.reload(true)
  }, 60 * 1000 * 3)
} else {
  // 加几秒的延迟，以免登录信息还未加载出来导致误判
  setTimeout(() => {
    if (
      (document.querySelector('.login-panel') || document.querySelector('#J_LoginBox')) &&
      location.href.indexOf('www.alimama.com/500.htm') === -1 &&
      ['/member/login.htm', '/member/login.jhtml'].indexOf(location.pathname) !== -1 &&
      location.search.indexOf('style=minisimple') === -1) {
      location.href = 'https://login.taobao.com/member/login.jhtml?style=minisimple&from=alimama&redirectURL=http://login.taobao.com/member/taobaoke/login.htm?is_login=1&full_redirect=true&c_isScure=true&quicklogin=true'
    }
  }, 6000)
}

// 用于进行恢复数据，不影响其他任务
if(location.href.indexOf('/report/detail/taoke?for=update') > 0) {
  let _tb_token_ = '';
  let startTime = '';
  let endTime = '';
  let abateStart = '';
  let queryType = 1;
  let day = 0;
  let month = 0;
  let year = 0;
  let req = null;
  let downloadBtn = null;
  let isForUpdate = false;
  let startRstTime = null;

  console.log('for=update')
  // 只能够获取最近90天的表单
  startRstTime = new Date('2017.10.19 0:0:0');
  let findBtnInterval = setInterval(() => {
    if (downloadBtn) {
      clearInterval(findBtnInterval);
      let newDownloadBtn = downloadBtn.cloneNode();
      let abateDownloadBtn = downloadBtn.cloneNode();  // 失效按钮
      let parent = downloadBtn.parentNode;
      parent.insertBefore(newDownloadBtn, downloadBtn);
      parent.insertBefore(abateDownloadBtn, downloadBtn);

      // 开始恢复数据，30s下载一天数据
      let rstInterval = setInterval(_ => {
        updateDate();
        // 判断数据恢复是否完成
        if ( new Date(startRstTime).getTime() >= new Date('2017.11.10 0:0:0') ) {
          clearInterval(rstInterval);
          console.log('数据恢复已结束');
        } else {
          console.log(startTime)
          // 结算
          newDownloadBtn.href = `/report/getTbkPaymentDetails.json?queryType=3&payStatus=3&DownloadID=DOWNLOAD_REPORT_INCOME_NEW&startTime=${startTime}&endTime=${startTime}`;
          downloadBtn.href = `/report/getTbkPaymentDetails.json?queryType=1&payStatus=&DownloadID=DOWNLOAD_REPORT_INCOME_NEW&startTime=${startTime}&endTime=${startTime}`;
          abateDownloadBtn.href = `/report/getTbkPaymentDetails.json?queryType=1&payStatus=13&DownloadID=DOWNLOAD_REPORT_INCOME_NEW&startTime=${startTime}&endTime=${startTime}`;
          setTimeout(_ => {
            newDownloadBtn.click();
          }, 1000);
          // 恢复暂时只爬结算的
          // setTimeout(_ => {
          //   abateDownloadBtn.click();
          // }, 2000);
          // downloadBtn.click();
        }
      }, 30000);
    } else {
      downloadBtn = document.querySelector('[title="下载报表"]');
    }
  }, 500);

  let updateDate = () => {
    let endDate = new Date();
    let startDate = startRstTime;
    let endYear = endDate.getFullYear();
    let startYear = startDate.getFullYear();
    let endMonth = endDate.getMonth() + 1;
    let startMonth = startDate.getMonth() + 1;
    let endDay = endDate.getDate();
    let startDay = startDate.getDate();
    if (endMonth < 10) {
      endMonth = '0' + endMonth.toString();
    }
    if (startMonth < 10) {
      startMonth = '0' + startMonth.toString();
    }
    if (endDay < 10) {
      endDay = '0' + endDay.toString();
    }
    if (startDay < 10) {
      startDay = '0' + startDay.toString();
    }
    endTime = endYear + '-' + endMonth + '-' + endDay;
    startTime = startYear + '-' + startMonth + '-' + startDay;
    startRstTime = new Date(startRstTime.getTime() + 60 * 1000 * 60 * 24);
    console.log(startRstTime.toLocaleString());
  }
}

/**
 *
 * @desc
 * @param {number} timeLog
 * @returns
 */
function delay (timeLog) {
  return new Promise((resolve) => {
    setTimeout(function() {
      resolve()
    }, timeLog);
  })
}

function resetLocalStorage () {
  localStorage.setItem('_umcost', '1823')
  localStorage.setItem('_umdata', "55F3A8BFC9C50DDAD984FBB8E9A5DC24F62236015DFF331938DA8962865764E92D86CA9DE876323CCD43AD3E795C914CEC9337B5B9455AE60CF2CD5F9F322E57")
  localStorage.setItem('_umtk', "{'t':1503381291747,'tk':'HV01PAAZ0b8712653cbf4612599bc72b002c0bfb'}")
}

// to fuck the ali's network limitation
if (location.href.indexOf('alisec.alimama.com/checkcodev3') !== -1) {
  let unlockId = setInterval(() => {
    let btn = document.querySelector('#nc_1_n1z');
    let bg = document.querySelector('#nc_1__bg');
    if (btn && bg) {
      clearInterval(unlockId)
      setTimeout(_ => {
        let mouseDownStart = new MouseEvent('mousedown', {
          clientX: 800,
          clientY: 400,
          view: window,
          buttons: 1,
          button: 0,
          bubbles: true,
          cancelable: true
        })

        // reset，因为淘宝登录页对这个值的设置有interval更新
        // resetLocalStorage()
        let mouseDown = new MouseEvent('mousedown', {
          clientX: 800,
          clientY: 400,
          view: window,
          buttons: 1,
          button: 0,
          bubbles: true,
          cancelable: true
        })

        // reset，因为淘宝登录页对这个值的设置有interval更新
        // resetLocalStorage()
        let mouseMove = new MouseEvent('mousemove', {
          clientX: 800,
          clientY: 400,
          view: window,
          buttons: 1,
          button: 0,
          bubbles: true,
          cancelable: true
        })

        btn.dispatchEvent(mouseDownStart);

        document.dispatchEvent(mouseMove);

        setTimeout(() => {
          btn.style.left = '58px';
          bg.style.width = '58px';
        }, 500)


        setTimeout(() => {
          btn.style.left = '100px';
          bg.style.width = '100px';
        }, 1000)

        setTimeout(() => {
          btn.style.left = '120px';
          bg.style.width = '120px';
        }, 1500)

        setTimeout(() => {
          btn.style.left = '158px';
          bg.style.width = '158px';
        }, 2000)

        setTimeout(() => {
          btn.style.left = '200px';
          bg.style.width = '200px';
        }, 2500)

        setTimeout(() => {
          btn.style.left = '220px';
          bg.style.width = '220px';
        }, 3000)

        setTimeout(() => {
          btn.style.left = '230px';
          bg.style.width = '230px';
        }, 3500)

        setTimeout(() => {
          btn.style.left = '258px';
          bg.style.width = '258px';
        }, 4000)

        setTimeout(() => {
          btn.dispatchEvent(mouseDown);
          document.dispatchEvent(mouseMove);
        }, 4500)
      }, 1500)
    }
  }, 500)
  // 验证失败后1min后重开
  setTimeout(() => {
    chrome.runtime.sendMessage({type: 'close-tab'})
  }, 60 * 1 * 1000)
}

// start auth
if (location.href.indexOf('oauth.taobao.com/authorize') !== -1) {
  let button = null
  let subBtnInterval = setInterval(() => {
    button = document.querySelector('#sub')
    if (button) {
      clearInterval(subBtnInterval)
      button.click()
    }
  }, 500)
}